package org.struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.struts.util.FullForm;

import com.guava.action.UserAction;

public class ActionServlet extends HttpServlet{

	private static final long serialVersionUID = -1223023820299465167L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String path = getPath(req);
		
		Map<String,XMLBean> map = (Map<String, XMLBean>) this.getServletContext().getAttribute("strutsMap");
		XMLBean bean = map.get(path);
		ActionForm form = FullForm.fullForm(req, bean.getBeanType());
		Action action = null;
		String url = "";
		try {
			action = (Action) Class.forName(bean.getActionType()).newInstance();
			String name = action.execute(req,form,resp);
			url = bean.getForwardMap().get(name);
			
		} catch (Exception e) {
			e.printStackTrace();
		
		}
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		this.doGet(req, resp);
	}
	
	public String getPath(HttpServletRequest req){
		String[] arr = req.getServletPath().split("\\.");
		return arr[0];
	}
}
